<template>
  <div class="digital-cockpit">
    <!-- 顶部导航 -->
    <van-nav-bar
        title="执行器配置"
        left-arrow
        @click-left="goBack"
        class="nav-bar"
    />
    <van-steps :active="configStep" active-icon="success" active-color="#27C2AD">
      <van-step>参数配置</van-step>
      <van-step>执行器配置</van-step>
    </van-steps>

    <div v-if="configStep === 0" class="config-step">
      <van-form
          v-if="paramForm.parameters && paramForm.parameters.length"
          ref="paramForm"
      >
        <van-row gutter="16">
          <van-col span="24">
            <van-cell-group>
              <div v-for="(record, index) in paramForm.parameters" :key="index" class="param-row">
                <!-- 参数名称 -->
                <van-field
                    v-model="record.lable"
                    label="参数名称"
                    placeholder="参数名称"
                    :disabled="record.isFixedName"
                    input-align="right"
                />

                <!-- 字符串/固定值输入 -->
                <van-field
                    v-if="record.valueType === 'string' || record.valueType === 'fixed'"
                    label="参数值"
                    v-model="record.value"
                    :placeholder="'请输入'+ record.lable"
                    :disabled="record.valueType === 'fixed' && record.isFixedType"
                    input-align="right"
                />

                <!-- 下拉多选 -->
                <van-field
                    v-if="record.valueType === 'select'"
                    label="参数值"
                    readonly
                    clickable
                    :value="getSelectedLabels(record)"
                    :placeholder="'请选择'+ record.lable +'(下拉多选)'"
                    :disabled="!record.options || record.options.length === 0"
                    input-align="right"
                    @click="showMultiSelect(record)"
                />
              </div>
            </van-cell-group>
          </van-col>


        </van-row>
      </van-form>
      <van-empty v-else description="此能力无需参数配置" />

      <!-- 多选弹出层 -->
<!--      <van-popup-->
<!--          v-model="showMultiSelectPopup"-->
<!--          position="bottom"-->
<!--          round-->
<!--          style="height: 30%;"-->
<!--      >-->
<!--        <div class="multi-select-header">-->
<!--          <div style="padding: 10px;">请选择{{ currentSelectRecord ? currentSelectRecord.lable : '' }}</div>-->
<!--        </div>-->

<!--        <van-checkbox-group v-model="currentSelectValues">-->
<!--          <van-cell-group>-->
<!--            <van-cell-->
<!--                v-for="(option, idx) in currentSelectOptions"-->
<!--                :key="idx"-->
<!--                clickable-->
<!--                @click="toggleOption(option.value)"-->
<!--            >-->
<!--              <template #right-icon>-->
<!--                <van-checkbox :name="option.value" />-->
<!--              </template>-->
<!--              {{ option.label || '未命名选项' }}-->
<!--            </van-cell>-->
<!--          </van-cell-group>-->
<!--        </van-checkbox-group>-->

<!--        <div class="multi-select-footer">-->
<!--          <van-button type="primary" class="ok-btn2" block @click="confirmMultiSelect">确定</van-button>-->
<!--        </div>-->
<!--      </van-popup>-->
      <van-popup
          v-model="showMultiSelectPopup"
          position="bottom"
          round
          style="height: 30%; display: flex; flex-direction: column;"
      >
        <div class="multi-select-header">
          <div style="padding: 10px;">请选择{{ currentSelectRecord ? currentSelectRecord.name : '' }}</div>
        </div>

        <div style="flex: 1; overflow-y: auto;">
          <van-checkbox-group v-model="currentSelectValues">
            <van-cell-group>
              <van-cell
                  v-for="(option, idx) in currentSelectOptions"
                  :key="idx"
                  clickable
                  @click="toggleOption(option.value)"
              >
                <template #right-icon>
                  <van-checkbox :name="option.value" />
                </template>
                {{ option.label || '未命名选项' }}
              </van-cell>
            </van-cell-group>
          </van-checkbox-group>
        </div>

        <div class="multi-select-footer">
          <van-button type="primary" class="ok-btn2" block @click="confirmMultiSelect">确定</van-button>
        </div>
      </van-popup>
    </div>

    <!-- 执行器配置步骤 -->
    <div v-if="configStep === 1" class="config-step">
      <div class="content-card">
        <van-loading v-if="isLoading || generatingCycle" class="loading-spinner" />
        <van-form
            v-show="!(isLoading || generatingCycle)"
            ref="dynamicValidateForm2"
            :rules="rules"
            :show-error-message="false"
            class="form-container"
        >
          <!-- 执行周期描述 -->
          <div class="form-item">
            <div class="form-label">执行周期描述</div>
            <div class="form-content cycle-description">
              <van-field
                  v-model="dynamicValidateForm2.description"
                  placeholder="请输入任务执行周期描述,可生成任务周期"
                  :border="false"
              />
              <van-button
                  type="primary"
                  size="small"
                  @click="generateTaskCycle"
                  :loading="generatingCycle"
                  loading-text="生成中..."
                  class="generate-btn"
              >
                生成任务周期
              </van-button>
            </div>


          </div>
          <!-- 生成结果展示 -->
          <div v-if="generationResult" class="generation-result-container">
            <div class="generation-result">
              <span class="result-label">生成结果:</span>
              <span class="result-value">{{ generationResult }}</span>
            </div>
          </div>
          <!-- 任务周期 -->
          <div class="form-item required">
            <div class="form-label">任务周期</div>
<!--            <div class="form-content">-->
<!--              <van-field-->
<!--                  :rules="rules.cycle"-->
<!--                  placeholder="请输入任务周期"-->
<!--                  v-model="dynamicValidateForm2.cycle"-->
<!--                  :border="false"-->
<!--                  class="input-with-icon"-->
<!--              >-->
<!--&lt;!&ndash;                <template #icon>&ndash;&gt;-->
<!--&lt;!&ndash;                  <van-icon name="calendar" class="calendar-icon" />&ndash;&gt;-->
<!--&lt;!&ndash;                </template>&ndash;&gt;-->
<!--              </van-field>-->
<!--            </div>-->

            <div class="form-content">
              <van-field
                  :rules="rules.cycle"
                  placeholder="请输入任务周期"
                  v-model="dynamicValidateForm2.cycle"
                  :border="false"
                  class="input-with-icon"
                  readonly
                  clickable
                  @click="showCronPicker = true"
              >
                <template #right-icon>
                  <van-icon name="calendar" class="calendar-icon" />
                </template>
              </van-field>
            </div>
          </div>

          <!-- 通知方式 -->
          <div class="form-item required">
            <div class="form-label">通知方式</div>
            <div class="form-content">
              <van-checkbox-group v-model="dynamicValidateForm2.type" direction="horizontal">
                <van-checkbox
                    v-for="option in abilityTypes2"
                    :key="option.value"
                    :name="option.value"
                    shape="square"
                >
                  {{ option.label || option.text }}
                </van-checkbox>
              </van-checkbox-group>
            </div>
          </div>

          <!-- 密信群KEY -->
          <div v-if="dynamicValidateForm2.type.includes('密信')" class="form-item required">
            <div class="form-label">密信群KEY</div>
            <div class="form-content">
              <van-field
                  :rules="rules.mixinKEY"
                  v-model="dynamicValidateForm2.mixinKEY"
                  :border="false"
                  placeholder="请输入密信群KEY"
              />
            </div>
          </div>

          <!-- 密信群名称 -->
          <div v-if="dynamicValidateForm2.type.includes('密信')" class="form-item required">
            <div class="form-label">密信群名称</div>
            <div class="form-content">
              <van-field
                  :rules="rules.mixinname"
                  v-model="dynamicValidateForm2.mixinname"
                  :border="false"
                  placeholder="请输入密信群名称"
              />
            </div>
          </div>

          <!-- 是否需要@人 -->
          <div v-if="dynamicValidateForm2.type.includes('密信')" class="form-item">
            <div class="form-label">是否需要@人</div>
            <div class="form-content">
              <van-switch
                  v-model="dynamicValidateForm2.isAt"
                  active-color="#27C2AD"
                  active-text="是"
                  inactive-text="否"
                  class="at-switch"
              />
            </div>
          </div>

          <!-- @的人手机号 -->
          <div
              v-if="dynamicValidateForm2.type.includes('密信') && dynamicValidateForm2.isAt"
              class="form-item required"
          >
            <div class="form-label">@的人手机号</div>
            <div class="form-content">
              <van-field
                  :rules="rules.atList"
                  v-model="dynamicValidateForm2.atList"
                  :border="false"
                  placeholder="多个手机号请用|分隔开"
              />
            </div>
          </div>

          <!-- 短信通知手机号 -->
          <div v-if="dynamicValidateForm2.type.includes('短信')" class="form-item required">
            <div class="form-label">手机号</div>
            <div class="form-content">
              <van-field
                  :rules="rules.phone"
                  v-model="dynamicValidateForm2.phone"
                  :border="false"
                  placeholder="请输入手机号"
              />
            </div>
          </div>
        </van-form>
      </div>
    </div>

    <van-row>
      <van-col span="10" v-if="configStep > 0" type="primary" @click="configStep--">
        <van-button class="last-btn">上一步</van-button>
      </van-col>
      <van-col span="14" v-if="configStep === 1" type="primary" @click="handleCombinedSubmit">
        <van-button type="primary" class="ok-btn">完成配置</van-button>
      </van-col>
      <van-col span="24" v-if="configStep < 1" type="primary" @click="next2()">
        <van-button
            type="primary"
            class="next-btn">
          下一步
        </van-button>
      </van-col>
    </van-row>

    <van-popup
        v-model="showCronPicker"
        position="bottom"
        round
        style="height: 80%;"
    >
      <div class="cron-picker-container">
        <van-tabs v-model="cronActiveTab" sticky>
          <van-tab title="简单配置">
            <div class="cron-simple-config">
              <van-radio-group v-model="simpleCronType">
                <van-cell-group>
                  <van-cell title="每分钟" clickable @click="simpleCronType = 'minute'">
                    <template #right-icon>
                      <van-radio name="minute" />
                    </template>
                  </van-cell>
                  <van-cell title="每小时" clickable @click="simpleCronType = 'hourly'">
                    <template #right-icon>
                      <van-radio name="hourly" />
                    </template>
                  </van-cell>
                  <van-cell title="每天" clickable @click="simpleCronType = 'daily'">
                    <template #right-icon>
                      <van-radio name="daily" />
                    </template>
                  </van-cell>
                  <van-cell title="每周" clickable @click="simpleCronType = 'weekly'">
                    <template #right-icon>
                      <van-radio name="weekly" />
                    </template>
                  </van-cell>
                  <van-cell title="每月" clickable @click="simpleCronType = 'monthly'">
                    <template #right-icon>
                      <van-radio name="monthly" />
                    </template>
                  </van-cell>
                </van-cell-group>
              </van-radio-group>

              <!-- 时间选择 -->
              <div class="time-picker" v-if="simpleCronType !== 'minute' && simpleCronType !== 'hourly'">
                <van-field
                    label="执行时间"
                    v-model="simpleCronTime"
                    type="time"
                    placeholder="选择时间"
                />
              </div>

              <!-- 星期选择 -->
              <div class="week-picker" v-if="simpleCronType === 'weekly'">
                <van-checkbox-group v-model="simpleCronWeekDays" direction="horizontal">
                  <van-checkbox name="1">周一</van-checkbox>
                  <van-checkbox name="2">周二</van-checkbox>
                  <van-checkbox name="3">周三</van-checkbox>
                  <van-checkbox name="4">周四</van-checkbox>
                  <van-checkbox name="5">周五</van-checkbox>
                  <van-checkbox name="6">周六</van-checkbox>
                  <van-checkbox name="7">周日</van-checkbox>
                </van-checkbox-group>
              </div>

              <!-- 预览 -->
              <div class="cron-preview" v-if="advancedCronExpression">
                <p>生成的表达式: <code>{{ advancedCronExpression }}</code></p>
                <p>说明: {{ cronDescription }}</p>
              </div>
            </div>
          </van-tab>

          <van-tab title="高级配置">
            <div class="cron-advanced-config">
              <van-field
                  v-model="advancedCronExpression"
                  label="CRON表达式"
                  placeholder="如: 0 0 8 * * ?"
                  clearable
              />
              <div class="cron-description">
                <p>表达式格式: <code>秒 分 时 日 月 周</code></p>
                <p>特殊字符说明:</p>
                <ul>
                  <li><code>*</code>: 表示任意值</li>
                  <li><code>?</code>: 表示不指定值(仅用于日和周的冲突解决)</li>
                  <li><code>-</code>: 表示范围，如 1-5</li>
                  <li><code>,</code>: 表示列举值，如 1,3,5</li>
                  <li><code>/</code>: 表示间隔频率，如 */5</li>
                </ul>
                <p>示例:</p>
                <ul>
                  <li>每分钟: <code>0 * * * * ?</code></li>
                  <li>每小时: <code>0 0 * * * ?</code></li>
                  <li>每天8点: <code>0 0 8 * * ?</code></li>
                  <li>每周一8点: <code>0 0 8 * * 1</code></li>
                  <li>每月1日8点: <code>0 0 8 1 * ?</code></li>
                </ul>
              </div>
            </div>
          </van-tab>
        </van-tabs>

        <div class="cron-picker-footer">
          <van-button type="default" @click="showCronPicker = false">取消</van-button>
          <van-button type="primary" @click="confirmCronExpression">确定</van-button>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script>
import { getAction,postAction } from '@/api'
export default {
  name: "index",
  data(){
    return{
      showTypePicker:false,
      configStep:0,
      currentAbility: null,
      paramForm: {
        parameters: [] // 参数列表
      },
      showMultiSelectPopup: false,
      currentSelectRecord: null,
      currentSelectValues: [],
      currentSelectOptions: [],

      isLoading:false,
      generatingCycle:false,
      dynamicValidateForm2:{
        description:'',
        cycle:'',
        type:[],
        mixinKEY:'',
        mixinname:'',
        phone:'',
        isAt:false,
        atList:''
      },
      rules: {
        cycle: [{ required: true, message: '请输入任务周期', trigger: 'onBlur' }],
        type: [{ required: true, message: '请选择通知方式', trigger: 'onChange' }],
        mixinKEY: [{ required: true, message: '请输入密信群KEY', trigger: 'onBlur' }],
        mixinname: [
          { required: true, message: '请输入密信群名称', trigger: 'onBlur' }
        ],
        atList: [
          { required: true, message: '请输入@的人手机号', trigger: 'onBlur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'onBlur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'onBlur' }
        ]
      },
      abilityTypes2:[
        { text: '密信', value: '密信' },
        { text: '短信', value: '短信' }
      ],
      generationResult:'',

      toOutboundItem:'',
      toOutboundsaveorupdate: '',
      item:'',
      activeTab:'',

      showCronPicker: false,
      cronActiveTab: 0,
      simpleCronType: 'daily',
      simpleCronTime: '08:00',
      simpleCronWeekDays: [],
      advancedCronExpression: '',
      cronDescription: ''
    }
  },
  mounted() {
    this.activeTab=this.$route.params.activeTab
    this.item=this.$route.params;
    this.handleButtonClick(this.$route.params)

    if (this.dynamicValidateForm2.cycle) {
      this.advancedCronExpression = this.dynamicValidateForm2.cycle;
      // 尝试解析已有表达式
      this.parseExistingCron();
    } else {
      this.updateSimpleCronPreview();
    }
  },
  watch: {
    simpleCronType() {
      this.updateSimpleCronPreview();
    },
    simpleCronTime() {
      this.updateSimpleCronPreview();
    },
    simpleCronWeekDays() {
      this.updateSimpleCronPreview();
    }
  },
  methods:{
    updateSimpleCronPreview() {
      let cron = '';
      let weekDays = '';
      let dayNames = '';
      const [hour, minute] = this.simpleCronTime.split(':');

      switch (this.simpleCronType) {
        case 'minute':
          cron = `0 * * * * ?`;
          this.cronDescription = '每分钟执行一次';
          break;
        case 'hourly':
          cron = `0 0 * * * ?`;
          this.cronDescription = '每小时执行一次';
          break;
        case 'daily':
          cron = `0 ${minute} ${hour} * * ?`;
          this.cronDescription = `每天${hour}:${minute}执行`;
          break;
        case 'weekly':
           weekDays = this.simpleCronWeekDays.length
              ? this.simpleCronWeekDays.join(',')
              : '?';
          // 修正点：日部分使用 ? 当指定了星期几时
          cron = `0 ${minute} ${hour} ? * ${weekDays}`;
          dayNames = this.simpleCronWeekDays.map(day => {
            const days = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
            return days[parseInt(day) - 1];
          }).join('、');
          this.cronDescription = this.simpleCronWeekDays.length
              ? `每周${dayNames}的${hour}:${minute}执行`
              : '请选择星期几';
          break;
        case 'monthly':
          cron = `0 ${minute} ${hour} 1 * ?`;
          this.cronDescription = `每月1日${hour}:${minute}执行`;
          break;
      }

      this.advancedCronExpression = cron;
    },
    confirmCronExpression() {
      if (this.cronActiveTab === 0) {
        // 简单配置模式
        if (this.simpleCronType === 'weekly' && this.simpleCronWeekDays.length === 0) {
          this.$toast('请至少选择一周中的某一天');
          return;
        }
        this.dynamicValidateForm2.cycle = this.advancedCronExpression;
      } else {
        // 高级配置模式
        if (this.validateCronExpression(this.advancedCronExpression)) {
          this.dynamicValidateForm2.cycle = this.advancedCronExpression;
        } else {
          this.$toast('请输入有效的CRON表达式');
          return;
        }
      }
      this.showCronPicker = false;
    },
    validateCronExpression(cron) {
      // XXL-JOB的CRON表达式验证
      const parts = cron.split(' ');
      if (parts.length !== 6) return false;

      // 简单的格式验证
      try {
        if (parts[3] !== '?' && parts[3] !== '*' && parts[5] !== '?' && parts[5] !== '*') {
          return false;
        }
        // 验证秒部分
        if (!this.validateCronPart(parts[0], 0, 59)) return false;
        // 验证分钟部分
        if (!this.validateCronPart(parts[1], 0, 59)) return false;
        // 验证小时部分
        if (!this.validateCronPart(parts[2], 0, 23)) return false;
        // 验证日期部分
        if (!this.validateCronPart(parts[3], 1, 31, true)) return false;
        // 验证月份部分
        if (!this.validateCronPart(parts[4], 1, 12, true)) return false;
        // 验证星期部分
        if (!this.validateCronPart(parts[5], 1, 7, true)) return false;

        // 检查日和周的冲突(不能同时指定具体值)
        if (parts[3] !== '?' && parts[3] !== '*' && parts[5] !== '?' && parts[5] !== '*') {
          return false;
        }

        return true;
      } catch (e) {
        return false;
      }
    },
    validateCronPart(part, min, max, allowQuestionMark = false) {
      if (part === '*' || (allowQuestionMark && part === '?')) return true;

      // 处理逗号分隔的值
      const values = part.split(',');
      for (const value of values) {
        // 处理范围
        if (value.includes('-')) {
          const range = value.split('-');
          if (range.length !== 2) return false;
          const start = parseInt(range[0]);
          const end = parseInt(range[1]);
          if (isNaN(start) || isNaN(end) || start < min || end > max || start > end) {
            return false;
          }
        }
        // 处理步长
        else if (value.includes('/')) {
          const stepParts = value.split('/');
          if (stepParts.length !== 2) return false;
          const step = parseInt(stepParts[1]);
          if (isNaN(step) || step < 1) return false;
        }
        // 处理单个值
        else {
          const num = parseInt(value);
          if (isNaN(num) || num < min || num > max) {
            return false;
          }
        }
      }

      return true;
    },

    parseExistingCron() {
      if (!this.dynamicValidateForm2.cycle) return;

      const parts = this.dynamicValidateForm2.cycle.split(' ');
      if (parts.length !== 6) return;

      // 尝试识别常见模式
      if (parts[0] === '0' && parts[1] === '*' && parts[2] === '*' && parts[3] === '*' && parts[4] === '*' && parts[5] === '?') {
        this.simpleCronType = 'minute';
      } else if (parts[0] === '0' && parts[1] === '0' && parts[2] === '*' && parts[3] === '*' && parts[4] === '*' && parts[5] === '?') {
        this.simpleCronType = 'hourly';
      } else if (parts[0] === '0' && parts[3] === '*' && parts[4] === '*' && parts[5] === '?') {
        this.simpleCronType = 'daily';
        this.simpleCronTime = `${parts[2].padStart(2, '0')}:${parts[1].padStart(2, '0')}`;
      } else if (parts[0] === '0' && parts[5] !== '?' && parts[5] !== '*') {
        this.simpleCronType = 'weekly';
        this.simpleCronTime = `${parts[2].padStart(2, '0')}:${parts[1].padStart(2, '0')}`;
        this.simpleCronWeekDays = parts[5].split(',').filter(d => d >= 1 && d <= 7);
      } else if (parts[0] === '0' && parts[3] !== '*' && parts[3] !== '?') {
        this.simpleCronType = 'monthly';
        this.simpleCronTime = `${parts[2].padStart(2, '0')}:${parts[1].padStart(2, '0')}`;
      } else if (parts[0] === '0' && parts[3] === '?' && parts[5] !== '?' && parts[5] !== '*') {
        this.simpleCronType = 'weekly';
        this.simpleCronTime = `${parts[2].padStart(2, '0')}:${parts[1].padStart(2, '0')}`;
        this.simpleCronWeekDays = parts[5].split(',').filter(d => d >= 1 && d <= 7);
      }
    },


    goBack() {
      // let param={
      //   activeTab:this.$route.params.activeTab
      // }
      // this.$router.push({name: 'test', params: param})
      this.$router.go(-1);
    },
    getSelectedLabels(record) {
      if (!record || !record.value || !record.options) return '';
      return record.options
          .filter(opt => record.value.includes(opt.value))
          .map(opt => opt.label || opt.value)
          .join(', ');
    },
    showMultiSelect(record) {
      if (!record.options || record.options.length === 0) {
        this.$toast('暂无可选选项');
        return;
      }
      this.currentSelectRecord = record;
      this.currentSelectOptions = record.options;
      this.currentSelectValues = record.value ? [...record.value] : [];
      this.showMultiSelectPopup = true;
    },
    toggleOption(value) {
      const index = this.currentSelectValues.indexOf(value);
      if (index > -1) {
        this.currentSelectValues.splice(index, 1);
      } else {
        this.currentSelectValues.push(value);
      }
    },
    confirmMultiSelect() {
      if (this.currentSelectRecord) {
        this.$set(this.currentSelectRecord, 'value', [...this.currentSelectValues]);
      }
      this.showMultiSelectPopup = false;
    },
    handleCombinedSubmit() {
      if(this.activeTab==1) {
        // 个人保存定时任务配置&&参数配置
        this.savetoOutbound()
      }else {
        this.savetoOutbound2()
      }
    },
    savetoOutbound() {
      // 统一防重复点击检查 - 使用单一变量控制
      if (this.isLoading) {
        return;
      }

      // 使用Vant的表单校验方式
      this.$refs.dynamicValidateForm2.validate()
          .then(() => {
            // 校验通过
            this.isLoading = true;

            // 更新订阅状态
            this.item.mark = this.isSubscribed ? null : 'subscribed';

            // 第二步：订阅操作
            return postAction('/sys/cockpitabilitymarket/Subscribe', this.item);
          })
          .then(res => {
            if (res.code != 200) {
              throw new Error(res.msg || '订阅操作失败');
            }
            this.toOutboundItem.mark = res.result;
            // 处理参数
            const updatedParams = this.paramForm.parameters.map(param => {
              // eslint-disable-next-line no-unused-vars
              const { isFixedName, isFixedType, isRequired, ...rest } = param;
              return rest;
            });
            this.currentAbility.parameters = JSON.stringify(updatedParams);

            // 第三步：保存配置
            return postAction('/sys/cockpithaveability/Configurethecapabilitytimingcycleandrelatedparameters', {
              executorhandler: this.toOutboundItem.executorhandler || '',
              executorparam: this.toOutboundItem.executorparam || '',
              executorid: this.toOutboundItem.executorid || '',
              requesttype: this.toOutboundItem.requesttype,
              name: this.toOutboundItem.name,
              mark: this.toOutboundItem.mark,
              types: this.toOutboundItem.type,
              url: this.toOutboundItem.url,
              header: this.toOutboundItem.header,
              parameters: this.currentAbility.parameters || '[]',
              type: JSON.stringify(this.dynamicValidateForm2.type),
              mixinKEY: this.dynamicValidateForm2.mixinKEY,
              mixinname: this.dynamicValidateForm2.mixinname,
              cycle: this.dynamicValidateForm2.cycle,
              isAt: this.dynamicValidateForm2.isAt,
              phone: this.dynamicValidateForm2.phone,
              atList: this.dynamicValidateForm2.atList,
              toOutboundsaveorupdate: this.toOutboundsaveorupdate
            });
          })
          .then(res => {
            if (res.code != 200) {
              throw new Error((res.message || '配置保存失败') + ',请检查表达式是否合规');
            }
            this.$toast.success(this.isSubscribed ? '取消订阅成功' : '订阅成功');
            this.goBack()
          })
          .catch(err => {
            if (err === 'validation-failed') {
              // 这是表单校验失败的错误
              this.$toast.fail('请填写完整信息');
            } else {
              // 其他错误
              this.$toast.fail(err.message || '操作失败，请稍后重试');
              // 恢复订阅状态（仅在订阅失败时）
              if (err.message.includes('订阅')) {
                this.item.mark = this.isSubscribed ? 'subscribed' : null;
              }
            }
          })
          .finally(() => {
            this.isLoading = false;
          });
    },

    savetoOutbound2() {
      // 防重复提交检查
      if (this.toOutboundLoading) return;

      // 处理参数数据
      const updatedParams = this.paramForm.parameters.map(param => {
        // 复制参数但不包含UI状态属性
        // eslint-disable-next-line no-unused-vars
        const { isFixedName, isFixedType, isRequired, ...rest } = param;
        return rest;
      });
      this.currentAbility.parameters = JSON.stringify(updatedParams);

      // 使用Vant的表单校验
      this.$refs.dynamicValidateForm2.validate()
          .then(() => {
            // 校验通过，设置加载状态
            this.toOutboundLoading = true;

            // 发起请求
            return postAction('/sys/cockpithaveability/Configurethecapabilitytimingcycleandrelatedparameters', {
              executorhandler: this.toOutboundItem.executorhandler || '',
              executorparam: this.toOutboundItem.executorparam || '',
              executorid: this.toOutboundItem.executorid || '',
              requesttype: this.toOutboundItem.requesttype,
              name: this.toOutboundItem.name,
              mark: this.toOutboundItem.mark,
              types: this.toOutboundItem.type,
              url: this.toOutboundItem.url,
              header: this.toOutboundItem.header,
              parameters: this.currentAbility.parameters || '[]',
              type: JSON.stringify(this.dynamicValidateForm2.type),
              mixinKEY: this.dynamicValidateForm2.mixinKEY,
              mixinname: this.dynamicValidateForm2.mixinname,
              cycle: this.dynamicValidateForm2.cycle,
              isAt: this.dynamicValidateForm2.isAt,
              phone: this.dynamicValidateForm2.phone,
              atList: this.dynamicValidateForm2.atList,
              toOutboundsaveorupdate: this.toOutboundsaveorupdate
            });
          })
          .then(res => {
            if (res.code == 200) {
              this.$toast.success('配置成功');
              this.goBack();
            } else {
              throw new Error(res.message || '配置失败');
            }
          })
          .catch(err => {
            if (err === 'validation-failed') {
              // 表单校验失败
              this.$toast.fail('请填写完整信息');
            } else {
              // 其他错误
              console.error(err);
              this.$toast.fail(err.message || '保存失败，请稍后再试');
            }
          })
          .finally(() => {
            this.toOutboundLoading = false;
          });
    },

    setCorn(data) {
      this.dynamicValidateForm.cycle = data;
    },
    async generateTaskCycle() {
      this.generatingCycle = true; // 开始加载
      this.generationResult = ''; // 清空之前的结果

      try {
        var query = this.dynamicValidateForm2.description;
        const requestBody = {
          inputs: {},
          query: `${query}`,
          response_mode: "streaming",
          conversation_id: "",
          user: this.$store.getters.userid
        };

        const response = await fetch("/v1/chat-messages", {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer app-jjk6DRzf9Eg3FlMRyl0YYBq9`
          },
          body: JSON.stringify(requestBody)
        });

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }

        const reader = response.body.getReader();
        const decoder = new TextDecoder('utf-8');
        let buffer = '';
        let fullResponse = '';

        // eslint-disable-next-line no-constant-condition
        while (true) {
          const { done, value } = await reader.read();
          if (done) break;

          buffer += decoder.decode(value, { stream: true });

          const lines = buffer.split(/\r\n|\r|\n/);
          buffer = lines.pop();

          for (const line of lines) {
            if (line.startsWith('data: ')) {
              const jsonStr = line.substring(6).trim();
              if (jsonStr === '') continue;

              try {
                const data = JSON.parse(jsonStr);
                if ((data.event === 'agent_message' || data.event === 'message') && data.answer) {
                  const decodedAnswer = data.answer.replace(/\\u([\d\w]{4})/gi,
                      (match, grp) => String.fromCharCode(parseInt(grp, 16)));

                  fullResponse += decodedAnswer;
                }
              } catch (e) {
                console.error('解析JSON出错:', e, '原始数据:', jsonStr);
              }
            }
          }
        }

        // 保存生成结果
        this.generationResult = fullResponse.trim();

        // 检查响应是否符合 cron 表达式格式
        if (this.isValidCronExpression(this.generationResult)) {
          this.$toast.success('生成任务周期成功');
          this.dynamicValidateForm2.cycle = this.generationResult;
        } else {
          this.$toast.fail('生成的任务周期格式不正确,请检查任务描述或手动配置任务周期');
          console.warn('无效的任务周期格式:', this.generationResult);
        }

      } catch (error) {
        console.error('生成任务周期出错:', error);
        this.generationResult = `生成失败: ${error.message}`;
        this.$toast.fail('生成任务周期失败: ' + error.message);
      } finally {
        this.generatingCycle = false; // 结束加载
      }
    },
    isValidCronExpression(expression) {
      if (!expression) return false;

      // 处理多个连续空格
      const cronParts = expression.trim().split(/\s+/);

      // 检查部分数量 (6或7部分)
      if (cronParts.length < 6 || cronParts.length > 7) {
        return false;
      }

      // 别名映射
      const monthNames = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"];
      const dayNames = ["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"];

      // 验证每个字段
      const validations = [
        { index: 0, name: "秒", min: 0, max: 59 },          // 秒
        { index: 1, name: "分", min: 0, max: 59 },          // 分
        { index: 2, name: "时", min: 0, max: 23 },          // 时
        { index: 3, name: "日", min: 1, max: 31, special: "L?*W" },  // 日
        { index: 4, name: "月", min: 1, max: 12, aliases: monthNames },  // 月
        { index: 5, name: "周", min: 0, max: 7, aliases: dayNames, special: "?*L#" }  // 周
      ];

      // 验证第7部分：年（可选）
      if (cronParts.length === 7) {
        if (!this.validateCronPart(cronParts[6], 1970, 2099, "", [])) {
          return false;
        }
      }

      // 验证所有字段
      for (const {index, min, max, special = "", aliases = []} of validations) {
        if (!this.validateCronPart(cronParts[index], min, max, special, aliases)) {
          return false;
        }
      }

      // 检查日和周的互斥规则
      return this.checkDayWeekConflict(cronParts[3], cronParts[5]);
    },
    validateCronValue(value, min, max, special, aliases) {
      // 通配符
      if (value === "*" || value === "?") return true;

      // 特殊语法 (L, W 等)
      if (special && new RegExp(`[${special}]`).test(value)) {
        return true;
      }

      // 别名
      if (aliases.length > 0 && aliases.includes(value.toUpperCase())) {
        return true;
      }

      // 纯数字
      if (/^\d+$/.test(value)) {
        const num = parseInt(value, 10);
        return num >= min && num <= max;
      }

      return false;
    },
    validateSpecialSyntax(part, min, max) {
      // 处理最后一天逻辑 (L)
      if (part === "L") return true;

      // 处理工作日逻辑 (W)
      if (part === "LW") return true;             // 当月最后工作日
      if (/^\d+W$/.test(part)) {                  // 最近工作日
        const day = parseInt(part.replace("W", ""), 10);
        return day >= min && day <= max;
      }

      // 处理周最后一天逻辑 (6L = 最后周五)
      if (/^\d+L$/.test(part)) {
        const day = parseInt(part.replace("L", ""), 10);
        return day >= 1 && day <= 7;
      }

      // 处理第N个星期X (1#3 = 第3个周一)
      if (/^\d+#\d+$/.test(part)) {
        const [day, week] = part.split("#").map(Number);
        return day >= 1 && day <= 7 && week >= 1 && week <= 5;
      }

      return false;
    },
    checkDayWeekConflict(dayField, weekField) {
      // 允许以下组合:
      //  日=* 和 周=?
      //  日=? 和 周=*
      //  日=? 和 周=?
      //  日=* 和 周=*
      const isDayWildcard = ["*", "?"].includes(dayField);
      const isWeekWildcard = ["*", "?"].includes(weekField);

      // 两个字段都指定具体值时冲突
      return isDayWildcard || isWeekWildcard;
    },

    handleButtonClick(item){
      // 初始化参数配置
      this.toOutbound2(item);
      // 初始化执行器配置
      this.toOutbound(item);
      // 重置步骤
      this.configStep = 0;
    },
    toOutbound2(item) {
      this.currentAbility = item;
      try {
        const paramSource = item.content != null
            ? JSON.parse(JSON.parse(item.content)[0]).params
            : (item.parameters || '[]');

        // 解析参数（统一处理字符串和对象）
        let parameters = [];
        try {
          parameters = typeof paramSource === 'string'
              ? JSON.parse(paramSource)
              : paramSource;
        } catch (parseError) {
          console.error('参数解析失败', parseError);
          throw new Error('参数格式无效');
        }

        // 确保参数是数组形式
        if (!Array.isArray(parameters)) {
          console.warn('参数不是数组，自动包装', parameters);
          parameters = [parameters];
        }

        const remoteRequests = parameters.map(async (param) => {
          const isRequired = ['string', 'fixed', 'select'].includes(param.valueType);
          const processedParam = {
            ...param,
            isFixedName: isRequired,
            isFixedType: isRequired,
            isRequired: isRequired
          };
          if (param.valueType === 'select' && param.remoteConfig) {
            const config = param.remoteConfig;
            try {
              // 转换headers格式
              let headersObj = {};
              if (Array.isArray(config.headers)) {
                // 处理数组形式的headers: [{key: "...", value: "..."}]
                config.headers.forEach(header => {
                  headersObj[header.key] = header.value;
                });
              } else if (typeof config.headers === 'object' && config.headers !== null) {
                // 已经是对象形式，直接使用
                headersObj = {...config.headers};
              }
              // 构建符合test_interface接口的参数
              const requestConfigs = {
                method: config.method || 'GET',
                headers: headersObj || {},
              };
              // 如果是POST请求，添加body
              if ((config.method || 'GET').toUpperCase() === 'POST' && config.body) {
                requestConfigs.body = config.body;
              }

              // 调用后端接口
              const param = {
                url: config.url,
                config: requestConfigs
              };
              postAction('/aility/test_interface', param).then(res=>{
                // 处理响应数据
                const responseData = JSON.parse(res.message);
                // 增强路径解析函数
                const resolvePath = (obj, path) => {
                  if (!path) return obj;

                  const keys = path.split('.');
                  let current = obj;

                  for (const key of keys) {
                    if (current === null || current === undefined) {
                      console.error(`路径解析中断：在 '${key}' 处遇到 ${current}，完整路径: ${path}`);
                      return null;
                    }

                    // 处理数组索引格式 [0]
                    const arrayMatch = key.match(/(\w+)$$(\d+)$$/);

                    if (arrayMatch) {
                      const arrayName = arrayMatch[1];
                      const index = parseInt(arrayMatch[2], 10);

                      if (!Array.isArray(current[arrayName])) {
                        console.error(`路径解析错误：'${arrayName}' 不是数组`);
                        return null;
                      }

                      if (index >= current[arrayName].length) {
                        console.error(`数组下标越界：${arrayName}[${index}]，数组长度: ${current[arrayName].length}`);
                        return null;
                      }

                      current = current[arrayName][index];
                    }
                    // 处理普通属性
                    else {
                      if (!(key in current)) {
                        console.error(`属性不存在：obj.${key}`);
                        return null;
                      }
                      current = current[key];
                    }
                  }

                  return current;
                };
                // 获取数据
                console.log('远程API响应:', responseData);
                const data = resolvePath(responseData, config.arrayPath);
                // 详细记录路径解析结果
                console.log(`路径解析结果 [${config.arrayPath}]:`, data);
                if (!data) {
                  console.warn(`远程配置返回的数据路径解析失败: ${config.arrayPath}`);
                  processedParam.options = [];
                  return processedParam;
                }
                // 检查数据类型
                if (!Array.isArray(data)) {
                  // 如果不是数组，尝试将其包装成数组
                  const normalizedData = data ? [data] : [];
                  console.warn(`远程配置返回的数据路径不是数组 ${config.arrayPath}`, data);
                  processedParam.options = normalizedData.map(item => ({
                    label: item[config.labelField || 'label'],
                    value: item[config.valueField || 'value']
                  }));
                } else {
                  processedParam.options = data.map(item => ({
                    label: item[config.labelField || 'label'],
                    value: item[config.valueField || 'value']
                  }));
                }
              });
            } catch (error) {
              console.error('远程配置获取失败', error);
              // 保留现有选项或设置为空数组
              processedParam.options = param.options || [];
            }
          }
          return processedParam;
        });

        Promise.all(remoteRequests).then(processedParameters => {
          this.paramForm.parameters = processedParameters;
        });

      } catch (e) {
        console.error('参数解析失败', e);
        this.paramForm.parameters = [];
      }
    },
    toOutbound(item) {
      this.toOutboundItem = item;
      var params = {};
      params.executorhandler = this.toOutboundItem.executorhandler|| '';
      params.executorparam = this.toOutboundItem.executorparam|| '';
      params.executorid= this.toOutboundItem.executorid || '';
      getAction('/sys/cockpithaveability/getparameters', params).then(res => {
        if (res.success && res.result) {
          try {
            // 双重解析：content 是字符串化的 JSON 数组
            const contentArray = JSON.parse(res.result.content);
            // 数组的第一个元素是 JSON 字符串（需要再次解析）
            if (contentArray && contentArray.length > 0) {
              const contentObj = JSON.parse(contentArray[0]);
              // 获取实际需要的字段
              this.generationResult='';
              this.dynamicValidateForm2.description = '';
              this.dynamicValidateForm2.type = JSON.parse(contentObj.type);
              this.dynamicValidateForm2.mixinKEY = contentObj.mixinKEY;
              this.dynamicValidateForm2.mixinname = res.result.mixinname;
              this.dynamicValidateForm2.phone = res.result.phone
              this.dynamicValidateForm2.cycle = contentObj.cycle;
              this.dynamicValidateForm2.isAt = res.result.isAt;
              this.dynamicValidateForm2.atList = res.result.atList;
              this.toOutboundsaveorupdate = 'update';
            }else{
              this.generationResult='';
              this.dynamicValidateForm2.description = '';
              this.dynamicValidateForm2.type = [];
              this.dynamicValidateForm2.mixinKEY = '';
              this.dynamicValidateForm2.mixinname = '';
              this.dynamicValidateForm2.phone = this.$store.getters.phone
              this.dynamicValidateForm2.cycle= '';
              this.dynamicValidateForm2.isAt = false;
              this.dynamicValidateForm2.atList = '';
              this.toOutboundsaveorupdate = 'update';
            }
          } catch (e) {
            console.error("解析 content 字段出错:", e);
          }
        }else{
          this.generationResult='';
          this.dynamicValidateForm2.description = '';
          this.dynamicValidateForm2.type = [];
          this.dynamicValidateForm2.mixinKEY = '';
          this.dynamicValidateForm2.mixinname = '';
          this.dynamicValidateForm2.phone = this.$store.getters.phone
          this.dynamicValidateForm2.cycle= '';
          this.dynamicValidateForm2.isAt = false;
          this.dynamicValidateForm2.atList = '';
          this.toOutboundsaveorupdate = 'save';
        }
      });
    },

    next2(){
      this.configStep++
    },
  }
}
</script>

<style scoped>
.cron-picker-container {
  padding: 16px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.cron-simple-config,
.cron-advanced-config {
  flex: 1;
  overflow-y: auto;
  padding-bottom: 60px;
}

.time-picker,
.week-picker {
  padding: 16px;
}

.week-picker .van-checkbox {
  margin-right: 8px;
}

.cron-description {
  padding: 16px;
  font-size: 12px;
  color: #666;
}

.cron-description code {
  background: #f5f5f5;
  padding: 2px 4px;
  border-radius: 3px;
}

.cron-picker-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  padding: 8px 16px;
  background: #fff;
  border-top: 1px solid #ebedf0;
}

.cron-picker-footer .van-button {
  flex: 1;
  margin: 0 8px;
}

.input-with-icon {
  background-color: #f7f8fa;
  border-radius: 4px;
}

.calendar-icon {
  color: #1989fa;
}

.cron-preview {
  padding: 16px;
  margin-top: 16px;
  background-color: #f7f8fa;
  border-radius: 4px;
}

.cron-preview code {
  background-color: #e8e8e8;
  padding: 2px 4px;
  border-radius: 3px;
  font-family: monospace;
}


::v-deep .van-nav-bar__content{
  background: #F4FCFF;
}
.digital-cockpit{
  background: linear-gradient(180deg, #F4FCFE, #fff);
  /*background-color: #f7f8fa;*/
  min-height: 100vh;
}
/deep/ .van-dropdown-menu__bar{
  box-shadow: none !important;
}
/deep/ .van-dropdown-menu__title{
  padding-right: 25vh !important;
}
/deep/.van-cell{
  /*padding: 8px 0px !important;*/
}
/deep/.van-steps--horizontal{
  border-radius: 10px;
  margin: 10px;
  padding: 10px 108px 0;
}


.config-step {
  padding: 10px;
  border-radius: 10px;
}

.loading-spinner {
  display: block;
  margin: 20px auto;
}



.generate-btn {
  width: 100px;
}


.error-result {
  color: #ee0a24;
  background-color: #fef0f0;
}

.van-field__label {
  text-align: left;
}
.last-btn{
  margin-left: 30%;
  width: 60%;
  margin-top: 20px;
  border-radius: 32px;
  font-size: 18px;
  font-weight: 500;
  border: 1px solid #e5e3e3;
}
.ok-btn{
  width: 80%;
  margin-top: 20px;
  border-radius: 32px;
  font-size: 18px;
  font-weight: 500;
  background: linear-gradient(90deg, #26B1A1 , #6FD0B3);;
  border: none;
}
.ok-btn2{
  width: 80%;
  margin-left: 10%;
  margin-top: 10px;
  margin-bottom: 10px;
  border-radius: 32px;
  font-size: 18px;
  font-weight: 500;
  background: linear-gradient(90deg, #26B1A1 , #6FD0B3);;
  border: none;
}
/* 下一步按钮样式 */
.next-btn {
  margin-left: 20%;
  width: 60%;
  margin-top: 20px;
  border-radius: 32px;
  font-size: 18px;
  font-weight: 500;
  background: linear-gradient(90deg, #26B1A1 , #6FD0B3);;
  border: none;
}

/* 去掉按钮默认hover效果（可选） */
.next-btn::after {
  background-color: #0EAD63 !important;
}

/* 页面基础样式 */
.executor-config {
  background-color: #F7F8FA;
  min-height: 100vh;
  padding-bottom: 80px;
}

/* 步骤条样式 */
.steps-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #fff;
  margin: 10px;
  padding: 15px 40px;
  border-radius: 8px;
}
.step-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 50%;
}
.step-dot {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background: #00B42A;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  margin-bottom: 6px;
}
.step-item.active .step-dot {
  background: #00B42A;
}
.step-item .step-dot.completed {
  background: #00B42A;
  font-weight: bold;
}
.step-text {
  font-size: 14px;
  color: #86909C;
}
.step-item.active .step-text {
  color: #00B42A;
}
.step-text.completed {
  color: #00B42A;
}
.step-line {
  height: 2px;
  background: #E5E6EB;
  flex: 1;
  margin: 0 10px;
}

/* 内容卡片 */
.content-card {
  background: #fff;
  border-radius: 8px;
  padding: 10px;
}

.form-item {
  display: flex;
  margin-bottom: 20px;
  align-items: center;
}
.form-item.required .form-label::before {
  content: '*';
  color: #F53F3F;
  margin-right: 4px;
}
.form-label {
  width: 7em; /* 固定标签宽度，与label-width="7em"对齐 */
  color: #4E5969;
  font-size: 14px;
  padding-right: 10px;
  text-align: left;
}
.form-content {
  flex: 1;
  position: relative;
}

/* 执行周期描述 */
.cycle-description {
  display: flex;
  gap: 10px;
  align-items: center;
}

.generate-btn {
  padding: 0px;
  font-size: 10px;
  min-width: 60px;
  background: #27C2AD;
  border-color: #27C2AD;
}



.generation-result-container {
  margin-top: -5%;
  padding-left: 28%;
  width: 72%;
}

.generation-result {
  font-size: 14px;
/* 可以根据需要添加更多样式 */
  padding: 8px;
  background-color: #f5f5f5;
  border-radius: 4px;
}
.result-label {
  color: #27C2AD;
  margin-right: 4px;
}
.result-value {
  color: #1D2129;
}

/* 输入框样式 */
.van-field__control {
  font-size: 14px;
}
.input-with-icon {
  position: relative;
}
.calendar-icon {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  color: #86909C;
}
.dropdown-input .van-field__control {
  padding-right: 20px;
}
.dropdown-input .van-dropdown-item__content::after {
  border-color: #C9CDD4;
}

/* 开关样式 */
.at-switch {
  margin-left: 16px;
  margin-top: 5px;
  font-size: 15px;
  --van-switch-active-color: #27C2AD;
  --van-switch-height: 24px;
}

/* 底部按钮 */
.bottom-buttons {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  padding: 16px;
  background: #F7F8FA;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  display: flex;
  gap: 10px;
}
.prev-btn {
  flex: 1;
  height: 50px;
  border-radius: 25px;
  background: #fff;
  border: 1px solid #E5E6EB;
  color: #1D2129;
}
.submit-btn {
  flex: 2;
  height: 50px;
  border-radius: 25px;
  background: #0FC672;
  border: none;
  font-size: 16px;
}

/* 图标样式 */
.van-icon {
  width: 18px;
  height: 18px;
}
</style>
